<template>
    <span class="file-input-wrapper" @click="doClick" :title="title">
       <span v-if="$slots.default">
            <slot></slot>
        </span>
        <span class="file-input" v-else>
            <span v-if="fileName">{{ fileName }}</span>
            <span style="color:#999999" v-else>{{ placeholder }}</span>
        </span>
        <input type="file" ref="file" :multiple="multiple" :accept="accept" @change="fileChange"/>
    </span>
</template>
<script>
export default {
  name: 'FileInput',
  model: {
    prop: 'value',//指向props的参数名
    event: 'change'//事件名称
  },
  props: {
    value: null,
    multiple: {
      default: false
    },
    accept: {
      default: "*"
    },
    placeholder: {
      default: '未选择任何文件'
    }
  },
  data() {
    return {
      fileName: '',
      title: ''
    }
  },
  methods: {
    doClick(e) {
      this.$refs.file.value=""
      this.$refs.file.click(e)
    },
    fileChange(e) {
      let files = e.target.files;
      if (files.length == 0) {
        this.fileName = "";
        this.title = ''
        // this.value=null;
        this.$emit('change', []);
        return;
      }
      if (files.length == 1) {
        this.fileName = files[0].name;
        this.title = ''
      } else {
        this.fileName = files.length + "个文件"
        let names = [];
        for (let f of files) {
          names.push(f.name);
        }
        this.title = names.join('\n')
      }
      let fileArr = [];
      for (let f of files) {
        fileArr.push(f);
      }
      // this.value=fileArr;
      this.$emit('change', fileArr);
    }
  }
}
</script>
<style>
.file-input {
  min-width: 1px;
  position: relative;
  background-color: #ffffff;
  border-radius: 4px;
  border: 1px solid #eeeeee;
  display: inline-block;
  padding: 4px 10px;
  line-height: 1.5;
  font-size: 14px;
  transition: all linear .2s;
  box-sizing: border-box;
  -webkit-appearance: none;
  font-family: inherit;
  vertical-align: top;
  outline: none;
  width: 100%;
  height: 40px;
}

.file-input-wrapper input[type=file] {
  display: none;
}

.file-input span {
  height: 30px;
  line-height: 30px;;
}
</style>
